const { UserModel } = require('../schema/user.schema');
const { jwtSign } = require('../../shared');
const { ObjectId } = require('bson');
const Router = require('express').Router;
const { LoginRes, LoginResData  } = require('./dto/login.dto');
const { status } = require('../util/status');
const { HttpResponse } = require('../util/HttpResponse');
const { authMiddleware } = require('../middleware/auth.middleware');

const route = new Router();

route.post('/login', async (req, res) => {
    const { username, password } = req.body;
    const userModel = UserModel;
    const userItem = await userModel.findOne({ username, password });
    if (userItem) {
        const data = {
            username: userItem.username,
            _id: userItem._id.toHexString(),
        };
        const token = jwtSign(data);
        const loginResData = new LoginResData();
        loginResData.players = userItem.players;
        loginResData.token = token;

        const loginRes = new LoginRes('ok', status.SUCCESS, loginResData);

        res.send(loginRes);
        return ;
    }
    const notExistRes = new HttpResponse('用户不存在', status.LOGIN_FAIL_FOR_NOTEXIST);
    res.send(notExistRes);
});

route.post('/users/player',authMiddleware , async (req, res) => {
    const { _id } = req.user;
    const body = req.body;
    if (_id) {
        const id = new ObjectId(_id);
        const result = await UserModel.updateOne()
    }
})


exports.AuthRoute = route;
